(function () {
  const checkAllEl = document.querySelector(".checkAll");
  const checkboxEls = document.querySelectorAll("tr td input[type=checkbox]");

  checkAllEl.addEventListener("click", checkAll);
  function checkAll() {
    // const status = this.checked;
    for (let i = 0; i < checkboxEls.length; i++) {
      const curCheckbox = checkboxEls[i];
      curCheckbox.checked = this.checked;
    }
  }

  for (let i = 0; i < checkboxEls.length; i++) {
    checkboxEls[i].addEventListener("click", function () {
      checkAllEl.checked = Array.from(checkboxEls)
        .map((o) => o.checked)
        .every((v) => v);
    });
  }

  const thEls = document.querySelectorAll("th");
  const trEls = document.querySelectorAll("tbody tr");
  const tbodyEl = document.querySelector("tbody");
  for (let i = 0; i < thEls.length; i++) {
    thEls[i].addEventListener("click", function () {
      const inner = this.innerHTML;
      switch (inner) {
        case "编号":
        case "年龄":
          swapNo();
          break;
        case "姓名":
        case "职位":
          swapName();
          break;
      }
    });
  }

  function swapNo() {
    const trArr = Array.from(trEls);
    const newtr = trArr.sort((a, b) => {
      return (
        parseFloat(a.querySelector("td:nth-child(2)").innerHTML) -
        parseFloat(b.querySelector("td:nth-child(2)").innerHTML)
      );
    });

    for (let i = 0; i < newtr.length; i++) {
      // 会将已经有的DOM结构从原来的位置移动到这个容器的最后面
      tbodyEl.appendChild(newtr[i]);
    }
  }

  function swapName() {
    const trArr = Array.from(trEls);
    const newtr = trArr.sort((a, b) => {
      return a
        .querySelector("td:nth-child(2)")
        .innerHTML.localeCompare(
          b.querySelector("td:nth-child(2)").innerHTML,
          "zh"
        );
    });

    for (let i = 0; i < newtr.length; i++) {
      // 会将已经有的DOM结构从原来的位置移动到这个容器的最后面
      tbodyEl.appendChild(newtr[i]);
    }
  }
})();
